package com.example.s.utils;

import android.app.Activity;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.s.Activity.BaseActivity;
import com.example.s.R;
import com.google.android.material.tabs.TabLayout;

import java.io.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyUtils {

    private static MyUtils mMyUtils;
    private String TAG = "MyUtils";

    private MyUtils() {
    }

    public static synchronized MyUtils getInstance() {
        if (mMyUtils == null) {
            mMyUtils = new MyUtils();
        }
        return mMyUtils;
    }

//    public File uri2File(BaseActivity A, Uri uri) {
//
//        String img_path;
//        String[] proj = {MediaStore.Images.Media.DATA,};
//        Cursor actualimagecursor = A.managedQuery(uri, proj, null,
//                null, null);
//        if (actualimagecursor == null) {
//            img_path = uri.getPath();
//        } else {
//            int actual_image_column_index = actualimagecursor
//                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//            actualimagecursor.moveToFirst();
//            img_path = actualimagecursor
//                    .getString(actual_image_column_index);
//        }
//        return new File(img_path);
//    }

//    public  byte[] toByteArray(InputStream in) throws IOException {
//              ByteArrayOutputStream out=new ByteArrayOutputStream();
//              byte[] buffer=new byte[1024*4];
//              int n=0;
//              while ( (n=in.read(buffer)) !=-1) {
//                    out.write(buffer,0,n);
//               }
//              return out.toByteArray();
//        }


    public  String inputStreamToString(InputStream inputStream) {
        StringBuffer buffer = new StringBuffer();
        InputStreamReader inputStreamReader;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }


    public boolean isHasEmpty(String... arr) {
        for (String s : arr) {
            if (TextUtils.isEmpty(s))
                return true;
        }
        return false;
    }

    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public TabLayout setNavItem(Context context, TabLayout tabLayout, String[] titleArr) {
        for (int i = 0; i < titleArr.length; i++) {
            View view = LayoutInflater.from(context).inflate(R.layout.main_nav_top, null);
            TextView tv = view.findViewById(R.id.tv);
            tv.setText(titleArr[i]);
            tabLayout.getTabAt(i).setCustomView(view);
        }
        return tabLayout;
    }

    public void showEtContainerBySoftkey(View contentView, View container) {

        ViewGroup.LayoutParams layoutParams = container.getLayoutParams();
        Animation animation = AnimationUtils.loadAnimation(container.getContext(), R.anim.bottom_to_top);
        animation.setDuration(200);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                container.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                contentView.getWindowVisibleDisplayFrame(r);
                int displayHeight = r.bottom - r.top;
                int parentHeight = contentView.getHeight();
                int softKeyHeight = parentHeight - displayHeight;
                Log.v(TAG, "softKeyHeight:" + softKeyHeight);
                if (softKeyHeight == 0 && container.getVisibility() == View.VISIBLE) {
                    container.setVisibility(View.INVISIBLE);
                    contentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    if (layoutParams instanceof FrameLayout.LayoutParams) {
                        FrameLayout.LayoutParams layout = (FrameLayout.LayoutParams) layoutParams;
                        layout.setMargins(0, 0, 0, softKeyHeight);
                    } else {
                        LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams) layoutParams;
                        layout.setMargins(0, 0, 0, softKeyHeight);
                    }
                    container.startAnimation(animation);
                }

            }
        });
    }

    public String getDateString(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public String getDateString(Date date, boolean isTime) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    //读取raw下txt文件
    public String getFromRaw(Context context, int fileId) {
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        StringBuilder result = new StringBuilder();
        try {
            inputReader = new InputStreamReader(context.getResources().openRawResource(fileId));
            bufReader = new BufferedReader(inputReader);
            String line = "";
            while ((line = bufReader.readLine()) != null)
                result.append(line);
            Log.d(TAG, "getFromRaw: 返回区域JSON");
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bufReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result.toString();
    }

    //震动milliseconds毫秒
    public void vibrate(final Activity activity, long milliseconds) {
        Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
        vib.vibrate(milliseconds);
        Log.d(TAG, "vibrate: 震动");
    }

    /**
     * 保存图片到sdk 并通知到相册
     *
     * @param resource
     */
    public void saveImage(Activity context, Bitmap resource) {
        String saveImagePath = null;
        String imageFileName = "Light" + "图片下载" + System.currentTimeMillis() + ".jpg";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory
                (Environment.DIRECTORY_PICTURES) + "pic");

        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
            Log.d(TAG, "saveImage: " + success);
        }
        if (success) {
            File imageFile = new File(storageDir, imageFileName);
            saveImagePath = imageFile.getAbsolutePath();
            try {
                OutputStream fout = new FileOutputStream(imageFile);
                resource.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Add the image to the system gallery
            galleryAddPic(context, saveImagePath);
            Toast.makeText(context, "保存成功", Toast.LENGTH_LONG).show();
        }
    }


    /**
     * 图片通知到到相册
     *
     * @param imagePath
     */
    private void galleryAddPic(Activity context, String imagePath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(imagePath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
        Log.d(TAG, "galleryAddPic: 通知相册");
    }

}
